/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package argentracker.activeentity.property;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;

import argentracker.activeentity.ActiveEntity;
import argentracker.activeentity.P;
import argentracker.activeentity.exceptions.ActiveEntityException;

/**
 * briefly description.
 * 
 * extense description.
 * 
 * @author matero (matero _at_ gmail _dot_ com)
 */
public class ReferenceProperty<R extends ActiveEntity<R>, AE extends ActiveEntity<AE>> extends P<R, AE> {

    private final Constructor<R> constructorWithEntity;
    private final Key traductedDefaultValue;

    /**
     * Constructs an Boolean property with no name and <code>null</code> as default value.
     */
    public ReferenceProperty(Class<R> referencedClass) {
        this(referencedClass, NO_NAME, null);
    }

    /**
     * Construts an Boolean property defining its name, and setting <code>null</code> as default value.
     * 
     * @param propertyName
     */
    public ReferenceProperty(Class<R> referencedClass, String propertyName) {
        this(referencedClass, propertyName, null);
    }

    /**
     * Constructs an Boolean property defining its name and default value.
     * 
     * @param propertyName
     */
    public ReferenceProperty(Class<R> referencedClass, String propertyName, R propertyDefaultValue) {
        super(referencedClass, propertyName, propertyDefaultValue);
        constructorWithEntity = getConstructorWithEntityOn(referencedClass);
        traductedDefaultValue = propertyDefaultValue == null ? null : propertyDefaultValue.getKey();
    }

    private Constructor<R> getConstructorWithEntityOn(Class<R> referencedClass) {
        try {
            return referencedClass.getConstructor(Entity.class);
        } catch (SecurityException e) {
            throw new ActiveEntityException("Could not access to constructor with entity on [" + referencedClass + "].");
        } catch (NoSuchMethodException e) {
            throw new ActiveEntityException("Constructor with entity on [" + referencedClass + "] is NOT defined.");
        }
    }

    @Override
    public R interpret(Object value) {
        Key key = (Key) value;
        DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();

        try {
            return constructReferencedActiveEntityWith(datastoreService.get(key));
        } catch (EntityNotFoundException e) {
            throw new ActiveEntityException("raw data not found for key " + key);
        }
    }

    private R constructReferencedActiveEntityWith(Entity entity) {
        try {
            return constructorWithEntity.newInstance(entity);
        } catch (IllegalArgumentException e) {
            throw new ActiveEntityException("unspected error: [" + entity + "] is considered illegal!", e);
        } catch (InstantiationException e) {
            throw new ActiveEntityException("Could not instantiate [" + getType() + "] using [" + entity + "].", e);
        } catch (IllegalAccessException e) {
            throw new ActiveEntityException("Could not instantiate [" + getType() + "] using [" + entity
                    + "], the constructor is not accesible.", e);
        } catch (InvocationTargetException e) {
            throw new ActiveEntityException("Could not instantiate [" + getType() + "] using [" + entity
                    + "], the constructor invocation failed.", e);
        }
    }

    @Override
    public Object traduct(R value) {
        return value == null ? traductedDefaultValue : value.getKey();
    }
}
